package com.mcy.redisdemo.controller;

import com.mcy.redisdemo.util.RedisUtil;
import org.apache.commons.lang3.RandomStringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.concurrent.TimeUnit;

/**
 * @Author: CYW
 * @Date: 2021/1/17 00:02
 */
@RestController
@RequestMapping("/redis")
public class RedisController {

    @Autowired
    private RedisUtil redisUtil;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    /**
     * 定义一个手机号发验证码的次数count_和一个锁lock_
     * _后面放手机号作为唯一标识
     * 每请求一次,+1使用redis实现
     * 当count>3时,把锁设为 1,锁的有效时间为 1 天,再次请求返回fail
     */
    //发送次数,下划线后面是手机号作为唯一标识
    private String COUNT = "count_";
    //是否被锁
    private String LOCK = "lock_";

    /**
     * @Author: CYW
     * 获取验证码
     * @return
     */
      @PostMapping("/sendCode")
        public String sendCode(String phoneNumber){
          ValueOperations<String, String> opsForValue = stringRedisTemplate.opsForValue();

          // 生成6位随机数(验证码)
          String random = RandomStringUtils.randomNumeric(6);

          System.out.println(random);
          //把验证码存入redis中,有效时间两分钟(120秒)
          redisUtil.set(phoneNumber+"code",random,120);


        //每访问一次,次数 +1,如果 >3 次 则返回给用户信息
          redisUtil.incr(COUNT+phoneNumber,1);
          System.out.println("发送次数为:"+opsForValue.get(COUNT + phoneNumber));

          if (Integer.parseInt(opsForValue.get(COUNT+phoneNumber))>2){
                if ("lock".equals(redisUtil.get(LOCK+phoneNumber))) {
                    return "overThree";
                }
            }

            if (Integer.parseInt(opsForValue.get(COUNT+phoneNumber))>2){
                //锁一天手机号不让再次获取验证码
                redisUtil.set(LOCK+phoneNumber,"lock",24*60);
            }
          return phoneNumber;
      }


    /**
     * @Author: CYW
     * 获取验证码
     * @return
     */
    @PostMapping("/checkCode")
    public String checkCode(String code,String phoneNumber){
        System.out.println(code);

        System.out.println("手机号"+phoneNumber);

        System.out.println(redisUtil.get(phoneNumber+"code"));
        System.out.println(code.equals(redisUtil.get(phoneNumber+"code")));
        if (code.equals(redisUtil.get(phoneNumber+"code"))){
            //验证成功
            return "checkOK";
        }
        return "checkFail";
    }
}
